<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生管理 - 教学管理系统</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 0;
        }

        .container {
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: 250px;
            background-color: #2c3e50;
            color: white;
            padding-top: 20px;
        }

        .sidebar-header {
            padding: 0 20px 20px;
            border-bottom: 1px solid #3c5166;
        }

        .sidebar-header h2 {
            margin: 0;
            font-size: 20px;
        }

        .user-info {
            margin-top: 10px;
            font-size: 14px;
            opacity: 0.8;
        }

        .menu-section {
            padding: 10px 20px;
            font-size: 14px;
            color: rgba(255, 255, 255, 0.6);
            border-bottom: 1px solid #3c5166;
            margin-top: 15px;
        }

        .menu {
            list-style: none;
            padding: 0;
            margin: 20px 0;
        }

        .menu li {
            padding: 12px 20px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .menu li:hover {
            background-color: #3c5166;
        }

        .menu li.active {
            background-color: #3498db;
        }

        .menu a {
            color: white;
            text-decoration: none;
            display: block;
        }

        .content {
            flex: 1;
            padding: 20px;
        }

        .content-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
        }

        .content-header h1 {
            margin: 0;
            color: #333;
            font-size: 24px;
        }

        .btn-add {
            background-color: #27ae60;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .btn-add:hover {
            background-color: #219653;
        }

        .search-box {
            margin-bottom: 20px;
        }

        .search-box input {
            width: 300px;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .search-box button {
            padding: 8px 16px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-left: 8px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background-color: white;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            overflow: hidden;
        }

        table th,
        table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }

        table th {
            background-color: #f8f9fa;
            color: #333;
            font-weight: 600;
        }

        table tr:hover {
            background-color: #f5f5f5;
        }

        .action-btn {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 5px;
            font-size: 13px;
        }

        .action-btn.edit {
            background-color: #f39c12;
        }

        .action-btn.delete {
            background-color: #e74c3c;
        }

        .action-btn:hover {
            opacity: 0.9;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background-color: white;
            border-radius: 8px;
            padding: 30px;
            width: 500px;
            max-width: 90%;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .modal-title {
            margin: 0;
            font-size: 20px;
            color: #333;
        }

        .close-btn {
            background: none;
            border: none;
            font-size: 20px;
            cursor: pointer;
            color: #777;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #555;
            font-weight: 500;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }

        .form-actions {
            text-align: right;
            margin-top: 20px;
        }

        .form-actions button {
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .btn-cancel {
            background-color: #eee;
            color: #333;
            border: 1px solid #ddd;
            margin-right: 10px;
        }

        .btn-submit {
            background-color: #3498db;
            color: white;
            border: none;
        }

        .logout {
            margin-top: auto;
            padding: 20px;
        }

        .logout a {
            color: #e74c3c;
            text-decoration: none;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="sidebar">
            <div class="sidebar-header">
                <h2>教学管理系统</h2>
                <div class="user-info" th:if="${session.user}">
                    <span th:text="${session.user.username}">admin1</span> - 管理员
                </div>
            </div>
            <div class="menu-section">基础管理</div>
            <ul class="menu">
                <li><a href="/admin/dashboard">系统概览</a></li>
                <li><a href="/admin/teachers">教师管理</a></li>
                <li class="active"><a href="/admin/students">学生管理</a></li>
                <li><a href="/admin/courses">课程管理</a></li>
                <li><a href="/admin/classrooms">教室管理</a></li>
            </ul>

            <div class="menu-section">教务管理</div>
            <ul class="menu">
                <li><a href="/admin/course-selections">选课管理</a></li>
                <li><a href="/admin/grades">成绩管理</a></li>
            </ul>

            <div class="menu-section">系统设置</div>
            <ul class="menu">
                <li><a href="/admin/profile">个人信息</a></li>
            </ul>

            <div class="logout">
                <a href="/logout">退出登录</a>
            </div>
        </div>

        <div class="content">
            <div class="content-header">
                <h1>学生管理</h1>
                <button class="btn-add" onclick="openAddModal()">添加学生</button>
            </div>

            <div class="search-box">
                <input type="text" id="searchInput" placeholder="请输入学生姓名或学号">
                <button onclick="searchStudents()">搜索</button>
            </div>

            <table id="studentsTable">
                <thead>
                    <tr>
                        <th>学号</th>
                        <th>姓名</th>
                        <th>性别</th>
                        <th>专业</th>
                        <th>年级</th>
                        <th>入学日期</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="studentsList">
                    <!-- 学生数据将通过AJAX动态加载 -->
                </tbody>
            </table>
        </div>
    </div>

    <!-- 添加学生模态框 -->
    <div class="modal" id="addModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">添加学生</h3>
                <button class="close-btn" onclick="closeAddModal()">&times;</button>
            </div>
            <form id="addStudentForm">
                <div class="form-group">
                    <label for="studentId">学号</label>
                    <input type="text" id="studentId" name="studentId" required>
                </div>
                <div class="form-group">
                    <label for="name">姓名</label>
                    <input type="text" id="name" name="name" required>
                </div>
                <div class="form-group">
                    <label for="gender">性别</label>
                    <select id="gender" name="gender" required>
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="major">专业</label>
                    <input type="text" id="major" name="major" required>
                </div>
                <div class="form-group">
                    <label for="grade">年级</label>
                    <select id="grade" name="grade" required>
                        <option value="大一上">大一上</option>
                        <option value="大一下">大一下</option>
                        <option value="大二上">大二上</option>
                        <option value="大二下">大二下</option>
                        <option value="大三上">大三上</option>
                        <option value="大三下">大三下</option>
                        <option value="大四上">大四上</option>
                        <option value="大四下">大四下</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="birthDate">出生日期</label>
                    <input type="date" id="birthDate" name="birthDate" required>
                </div>
                <div class="form-group">
                    <label for="enrollmentDate">入学日期</label>
                    <input type="date" id="enrollmentDate" name="enrollmentDate" required>
                </div>
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" name="username" required>
                </div>
                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" name="password" required>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn-cancel" onclick="closeAddModal()">取消</button>
                    <button type="button" class="btn-submit" onclick="addStudent()">保存</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 编辑学生模态框 -->
    <div class="modal" id="editModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">编辑学生</h3>
                <button class="close-btn" onclick="closeEditModal()">&times;</button>
            </div>
            <form id="editStudentForm">
                <input type="hidden" id="editStudentId" name="studentId">
                <input type="hidden" id="editUserId" name="userId">
                <div class="form-group">
                    <label for="editName">姓名</label>
                    <input type="text" id="editName" name="name" required>
                </div>
                <div class="form-group">
                    <label for="editGender">性别</label>
                    <select id="editGender" name="gender" required>
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="editMajor">专业</label>
                    <input type="text" id="editMajor" name="major" required>
                </div>
                <div class="form-group">
                    <label for="editGrade">年级</label>
                    <select id="editGrade" name="grade" required>
                        <option value="大一上">大一上</option>
                        <option value="大一下">大一下</option>
                        <option value="大二上">大二上</option>
                        <option value="大二下">大二下</option>
                        <option value="大三上">大三上</option>
                        <option value="大三下">大三下</option>
                        <option value="大四上">大四上</option>
                        <option value="大四下">大四下</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="editBirthDate">出生日期</label>
                    <input type="date" id="editBirthDate" name="birthDate" required>
                </div>
                <div class="form-group">
                    <label for="editEnrollmentDate">入学日期</label>
                    <input type="date" id="editEnrollmentDate" name="enrollmentDate" required>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn-cancel" onclick="closeEditModal()">取消</button>
                    <button type="button" class="btn-submit" onclick="updateStudent()">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // 页面加载完成后获取学生列表
        document.addEventListener('DOMContentLoaded', function () {
            fetchStudents();
        });

        // 获取学生列表
        function fetchStudents() {
            console.log("开始获取学生列表...");
            fetch('/api/admin/students', {
                method: 'GET',
                credentials: 'include'
            })
                .then(response => {
                    console.log("获取学生列表响应状态:", response.status);
                    if (!response.ok) {
                        if (response.status === 401) {
                            console.error("未授权，需要重新登录");
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                        }
                        throw new Error('获取学生失败: ' + response.statusText);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log("成功获取学生列表数据:", data);
                    renderStudents(data);
                })
                .catch(error => {
                    console.error('获取学生列表失败:', error);
                    alert('获取学生列表失败: ' + error.message);
                });
        }

        // 渲染学生列表
        function renderStudents(students) {
            console.log("开始渲染学生列表...");
            const tableBody = document.getElementById('studentsList');
            tableBody.innerHTML = '';

            if (students.length === 0) {
                const row = document.createElement('tr');
                row.innerHTML = '<td colspan="7" style="text-align: center;">暂无学生数据</td>';
                tableBody.appendChild(row);
                console.log("学生列表为空");
                return;
            }

            students.forEach(student => {
                // 安全转义学生ID，防止特殊字符导致问题
                const safeId = student.studentId.replace(/'/g, "\\'").replace(/"/g, '\\"');
                
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${student.studentId}</td>
                    <td>${student.name}</td>
                    <td>${student.gender}</td>
                    <td>${student.major}</td>
                    <td>${student.grade}</td>
                    <td>${formatDate(student.enrollmentDate)}</td>
                    <td>
                        <button class="action-btn edit" data-id="${safeId}">编辑</button>
                        <button class="action-btn delete" data-id="${safeId}">删除</button>
                    </td>
                `;
                
                // 添加点击事件监听器
                const editButton = row.querySelector('.edit');
                const deleteButton = row.querySelector('.delete');
                
                editButton.addEventListener('click', function() {
                    console.log("编辑按钮被点击，学生ID:", safeId);
                    openEditModal(safeId);
                });
                
                deleteButton.addEventListener('click', function() {
                    console.log("删除按钮被点击，学生ID:", safeId);
                    deleteStudent(safeId);
                });
                
                tableBody.appendChild(row);
            });
            console.log(`成功渲染 ${students.length} 个学生`);
        }

        // 格式化日期
        function formatDate(dateString) {
            console.log('Formatting date:', dateString);
            if (!dateString) {
                console.log('Date string is empty or null');
                return '';
            }
            try {
                const date = new Date(dateString);
                if (isNaN(date.getTime())) {
                    console.log('Invalid date:', dateString);
                    return '';
                }
                const formattedDate = date.toISOString().split('T')[0];
                console.log('Formatted date:', formattedDate);
                return formattedDate;
            } catch (error) {
                console.error('Error formatting date:', error);
                return '';
            }
        }

        // 搜索学生
        function searchStudents() {
            const searchTerm = document.getElementById('searchInput').value.trim();
            console.log("开始搜索学生，关键词:", searchTerm);
            if (searchTerm === '') {
                fetchStudents();
                return;
            }

            fetch(`/api/admin/students/search?term=${encodeURIComponent(searchTerm)}`, {
                method: 'GET',
                credentials: 'include'
            })
                .then(response => {
                    console.log("搜索学生响应状态:", response.status);
                    if (!response.ok) {
                        if (response.status === 401) {
                            console.error("未授权，需要重新登录");
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                        }
                        throw new Error('搜索学生失败: ' + response.statusText);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log("搜索学生结果:", data);
                    renderStudents(data);
                })
                .catch(error => {
                    console.error('搜索学生出错:', error);
                    alert('搜索学生失败: ' + error.message);
                });
        }

        // 打开添加学生模态框
        function openAddModal() {
            document.getElementById('addStudentForm').reset();
            document.getElementById('addModal').style.display = 'flex';
        }

        // 关闭添加学生模态框
        function closeAddModal() {
            document.getElementById('addModal').style.display = 'none';
        }

        // 添加学生
        function addStudent() {
            const studentId = document.getElementById('studentId').value.trim();
            const name = document.getElementById('name').value.trim();
            const gender = document.getElementById('gender').value;
            const major = document.getElementById('major').value.trim();
            const grade = document.getElementById('grade').value;
            const birthDate = document.getElementById('birthDate').value;
            const enrollmentDate = document.getElementById('enrollmentDate').value;
            const username = document.getElementById('username').value.trim();
            const password = document.getElementById('password').value.trim();

            if (!studentId || !name || !major || !birthDate || !enrollmentDate || !username || !password) {
                alert('请填写所有必填字段');
                return;
            }

            const studentData = {
                studentId,
                name,
                gender,
                major,
                grade,
                birthDate,
                enrollmentDate,
                username,
                password
            };

            fetch('/api/admin/students', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(studentData)
            })
                .then(response => {
                    if (!response.ok) {
                        return response.text().then(text => {
                            throw new Error(text || '添加学生失败');
                        });
                    }
                    return response.json();
                })
                .then(() => {
                    closeAddModal();
                    fetchStudents();
                })
                .catch(error => {
                    console.error('添加学生失败:', error);
                    alert('添加学生失败: ' + error.message);
                });
        }

        // 打开编辑学生模态框
        function openEditModal(studentId) {
            console.log("准备打开编辑学生模态框，学生ID:", studentId);
            
            if (!studentId) {
                console.error("学生ID为空，无法打开编辑模态框");
                alert("错误：无法获取学生信息");
                return;
            }
            
            // 显示模态框并设置加载状态
            document.getElementById('editModal').style.display = 'flex';
            document.getElementById('editStudentForm').innerHTML = '<div style="text-align: center; padding: 20px;">加载中...</div>';
            
            fetch(`/api/admin/students/${encodeURIComponent(studentId)}`, {
                method: 'GET',
                credentials: 'include'
            })
                .then(response => {
                    console.log("获取学生详情响应状态:", response.status);
                    if (!response.ok) {
                        if (response.status === 401) {
                            console.error("未授权，需要重新登录");
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                        } else if (response.status === 404) {
                            alert('学生不存在');
                        }
                        throw new Error('获取学生详情失败: ' + response.statusText);
                    }
                    return response.json();
                })
                .then(student => {
                    console.log("成功获取学生详情:", student);
                    
                    // 恢复表单内容
                    document.getElementById('editStudentForm').innerHTML = `
                        <input type="hidden" id="editStudentId" name="studentId">
                        <input type="hidden" id="editUserId" name="userId">
                        <div class="form-group">
                            <label for="editName">姓名</label>
                            <input type="text" id="editName" name="name" required>
                        </div>
                        <div class="form-group">
                            <label for="editGender">性别</label>
                            <select id="editGender" name="gender" required>
                                <option value="男">男</option>
                                <option value="女">女</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="editMajor">专业</label>
                            <input type="text" id="editMajor" name="major" required>
                        </div>
                        <div class="form-group">
                            <label for="editGrade">年级</label>
                            <select id="editGrade" name="grade" required>
                                <option value="大一上">大一上</option>
                                <option value="大一下">大一下</option>
                                <option value="大二上">大二上</option>
                                <option value="大二下">大二下</option>
                                <option value="大三上">大三上</option>
                                <option value="大三下">大三下</option>
                                <option value="大四上">大四上</option>
                                <option value="大四下">大四下</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="editBirthDate">出生日期</label>
                            <input type="date" id="editBirthDate" name="birthDate" required>
                        </div>
                        <div class="form-group">
                            <label for="editEnrollmentDate">入学日期</label>
                            <input type="date" id="editEnrollmentDate" name="enrollmentDate" required>
                        </div>
                        <div class="form-actions">
                            <button type="button" class="btn-cancel" onclick="closeEditModal()">取消</button>
                            <button type="button" class="btn-submit" onclick="updateStudent()">保存</button>
                        </div>
                    `;
                    
                    // 填充表单数据
                    document.getElementById('editStudentId').value = student.studentId;
                    document.getElementById('editUserId').value = student.userId;
                    document.getElementById('editName').value = student.name;
                    document.getElementById('editGender').value = student.gender;
                    document.getElementById('editMajor').value = student.major;
                    document.getElementById('editGrade').value = student.grade;
                    document.getElementById('editBirthDate').value = formatDate(student.birthDate);
                    document.getElementById('editEnrollmentDate').value = formatDate(student.enrollmentDate);
                })
                .catch(error => {
                    console.error('获取学生详情出错:', error);
                    document.getElementById('editStudentForm').innerHTML = `
                        <div style="text-align: center; color: red; padding: 20px;">
                            加载失败: ${error.message}
                            <div class="form-actions" style="margin-top: 20px;">
                                <button type="button" class="btn-cancel" onclick="closeEditModal()">关闭</button>
                            </div>
                        </div>
                    `;
                });
        }

        // 关闭编辑学生模态框
        function closeEditModal() {
            document.getElementById('editModal').style.display = 'none';
        }

        // 更新学生
        function updateStudent() {
            const studentId = document.getElementById('editStudentId').value;
            const userId = document.getElementById('editUserId').value;
            const name = document.getElementById('editName').value.trim();
            const gender = document.getElementById('editGender').value;
            const major = document.getElementById('editMajor').value.trim();
            const grade = document.getElementById('editGrade').value;
            const birthDate = document.getElementById('editBirthDate').value;
            const enrollmentDate = document.getElementById('editEnrollmentDate').value;

            console.log("准备更新学生:", studentId);

            if (!name || !major || !birthDate || !enrollmentDate) {
                alert('请填写所有必填字段');
                return;
            }

            // 禁用保存按钮，防止重复提交
            const saveButton = document.querySelector('#editModal .btn-submit');
            const cancelButton = document.querySelector('#editModal .btn-cancel');
            
            if (saveButton) {
                saveButton.disabled = true;
                saveButton.textContent = '保存中...';
            }
            if (cancelButton) {
                cancelButton.disabled = true;
            }

            const student = {
                studentId,
                userId: parseInt(userId),
                name,
                gender,
                major,
                grade,
                birthDate,
                enrollmentDate
            };

            fetch(`/api/admin/students/${encodeURIComponent(studentId)}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                credentials: 'include',
                body: JSON.stringify(student)
            })
                .then(response => {
                    console.log("更新学生响应状态:", response.status);
                    if (!response.ok) {
                        if (response.status === 401) {
                            console.error("未授权，需要重新登录");
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                            throw new Error('未授权');
                        } else if (response.status === 404) {
                            alert('学生不存在');
                            throw new Error('学生不存在');
                        }
                        return response.text().then(text => { throw new Error(text || '更新学生失败') });
                    }
                    return response.json();
                })
                .then(data => {
                    console.log("更新学生成功:", data);
                    alert('更新学生成功');
                    closeEditModal();
                    fetchStudents(); // 刷新学生列表
                })
                .catch(error => {
                    console.error('更新学生出错:', error);
                    alert('更新学生失败: ' + error.message);
                })
                .finally(() => {
                    // 恢复按钮状态
                    if (saveButton) {
                        saveButton.disabled = false;
                        saveButton.textContent = '保存';
                    }
                    if (cancelButton) {
                        cancelButton.disabled = false;
                    }
                });
        }

        // 删除学生
        function deleteStudent(studentId) {
            console.log("删除学生，ID:", studentId);
            if (!confirm('确定要删除此学生吗？此操作不可恢复，将同时删除关联的用户信息和选课记录。')) {
                return;
            }

            fetch(`/api/admin/students/${encodeURIComponent(studentId)}`, {
                method: 'DELETE',
                credentials: 'include'
            })
                .then(response => {
                    console.log("删除学生响应状态:", response.status);
                    if (!response.ok) {
                        if (response.status === 401) {
                            console.error("未授权，需要重新登录");
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                        } else if (response.status === 404) {
                            alert('学生不存在');
                        }
                        return response.text().then(text => { throw new Error(text || '删除学生失败') });
                    }
                    return response.text();
                })
                .then(() => {
                    console.log("删除学生成功");
                    alert('删除学生成功');
                    fetchStudents();
                })
                .catch(error => {
                    console.error('删除学生出错:', error);
                    alert('删除学生失败: ' + error.message);
                });
        }
    </script>
</body>

</html>